package com.dy.nacos.utils;

import com.alibaba.fastjson.JSON;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.http.util.TextUtils;
import org.junit.jupiter.api.Test;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

/**
 * http客户端
 * @author huangdeyao
 */
public class HttpClientUtils {

    /**
     * post请求传输map数据
     *
     * @param url
     * @param map
     * @param encoding
     * @return
     * @throws ClientProtocolException
     * @throws IOException
     */
    public static String sendPostDataByMap(String url, Map<String, String> map, String encoding) throws ClientProtocolException, IOException {
        String result = "";

        // 创建httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        // 创建post方式请求对象
        HttpPost httpPost = new HttpPost(url);

        // 装填参数
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        if (map != null) {
            for (Entry<String, String> entry : map.entrySet()) {
                nameValuePairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            }
        }

        // 设置参数到请求对象中
        httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, encoding));

        // 设置header信息
        // 指定报文头【Content-type】、【User-Agent】
        httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
        httpPost.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");

        // 执行请求操作，并拿到结果（同步阻塞）
        CloseableHttpResponse response = httpClient.execute(httpPost);
        // 获取结果实体
        // 判断网络连接状态码是否正常(0--200都数正常)
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            result = EntityUtils.toString(response.getEntity(), "utf-8");
        }
        // 释放链接
        response.close();

        return result;
    }

    /**
     * post请求传输json数据
     *
     * @param url
     * @param json
     * @param encoding
     * @return
     * @throws ClientProtocolException
     * @throws IOException
     */
    public static String sendPostDataByJson(String url, String json, String encoding) throws ClientProtocolException, IOException {
        String result = "";

        // 创建httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();

        // 创建post方式请求对象
        HttpPost httpPost = new HttpPost(url);

        // 设置参数到请求对象中
        StringEntity stringEntity = new StringEntity(json, ContentType.APPLICATION_JSON);
        stringEntity.setContentEncoding("utf-8");
        httpPost.setEntity(stringEntity);

        // 执行请求操作，并拿到结果（同步阻塞）
        CloseableHttpResponse response = httpClient.execute(httpPost);

        // 获取结果实体
        // 判断网络连接状态码是否正常(0--200都数正常)
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            result = EntityUtils.toString(response.getEntity(), "utf-8");
        }
        // 释放链接
        response.close();

        return result;
    }

    /**
     * get请求传输数据
     *
     * @param url
     * @param encoding
     * @return
     * @throws ClientProtocolException
     * @throws IOException
     */
    public static String sendGetData(String url, String encoding) throws ClientProtocolException, IOException {
        String result = "";

        // 创建httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();

        // 创建get方式请求对象
        HttpGet httpGet = new HttpGet(url);
        httpGet.addHeader("Content-type", "application/json");
        // 通过请求对象获取响应对象
        CloseableHttpResponse response = httpClient.execute(httpGet);

        // 获取结果实体
        // 判断网络连接状态码是否正常(0--200都数正常)
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            result = EntityUtils.toString(response.getEntity(), "utf-8");
        }
        // 释放链接
        response.close();

        return result;
    }


    /**
     * 从网络Url中下载文件
     *
     * @param urlStr
     * @throws IOException
     */
    public static byte[] downLoadFile(String urlStr) throws IOException {
        URL url = new URL(urlStr);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        //
        /**
         * 设置超时间为3秒
         */
        conn.setConnectTimeout(3 * 1000);
        /**
         * 防止屏蔽程序抓取而返回403错误
         */
        conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
        /**
         * 得到输入流
         */
        InputStream inputStream = conn.getInputStream();
        /**
         * 获取自己数组
         */
        byte[] getData = readInputStream(inputStream);
        inputStream.close();
        return getData;
    }

    /**
     * 从输入流中获取字节数组
     *
     * @param inputStream
     * @return
     * @throws IOException
     */
    public static byte[] readInputStream(InputStream inputStream) throws IOException {
        byte[] buffer = new byte[1024];
        int len = 0;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        while ((len = inputStream.read(buffer)) != -1) {
            bos.write(buffer, 0, len);
        }
        bos.close();
        return bos.toByteArray();
    }

    public static byte[] doJsonPost(String urlPath, String Json) {
        String result = "";
        BufferedReader reader = null;
        try {
            URL url = new URL(urlPath);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setRequestProperty("Charset", "UTF-8");
            // 设置文件类型:
            conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
            // 设置接收类型否则返回415错误
            //conn.setRequestProperty("accept","*/*")此处为暴力方法设置接受所有类型，以此来防范返回415;
            conn.setRequestProperty("accept", "application/json");
            // 往服务器里面发送数据
            if (Json != null && !TextUtils.isEmpty(Json)) {
                byte[] writebytes = Json.getBytes();
                // 设置文件长度
                conn.setRequestProperty("Content-Length", String.valueOf(writebytes.length));
                OutputStream outwritestream = conn.getOutputStream();
                outwritestream.write(Json.getBytes());
                outwritestream.flush();
                outwritestream.close();
                System.out.printf("doJsonPost: conn" + conn.getResponseCode());
            }
            if (conn.getResponseCode() == 200) {
//                reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
//                result = reader.readLine();
                InputStream input = conn.getInputStream();
                ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
                byte[] buff = new byte[100];
                int rc = 0;
                while ((rc = input.read(buff, 0, 100)) > 0) {
                    swapStream.write(buff, 0, rc);
                }
                byte[] in2b = swapStream.toByteArray();
                return in2b;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    @Test
    public void testSendPostDataByMap() throws ClientProtocolException, IOException {
//        String couponToken = "http://10.5.72.55:8866/oauth/token?username=coupon&password=coupon2018*&client_secret=devglan-secret&client_id=devglan-client&grant_type=password";
//        String body = HttpClientUtils.sendGetData(couponToken, null);
//        JSONObject object =JSON.parseObject(body);
//        System.out.println("body:" + object.get("access_token"));
//        String couponCreate = "http://10.5.72.55:8866/markor/get/coupon?access_token=";
//        CreateCoupon coupon = new CreateCoupon();
//        coupon.setSource("1");
//        coupon.setOpenid("1234567890");
//        coupon.setActivityNo("110");
//        coupon.setChannelId("110");
//        coupon.setSystemId("wechatservice");
//        String str = JSON.toJSONString(coupon);
//        String body12 = HttpClientUtils.sendPostDataByJson(couponCreate + object.get("access_token"), str, null);
//        System.out.println("body12:" + body12);

    }

    @Test
    public void testSendPostDataByJson() throws ClientProtocolException, IOException {
        String url = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=13_DQn1Z3u9ZWyJB6iYeHkCye27ua67_mayLjAFWpLWCSr7diuZinl4ot5HE7RkW4eSiIbBc8kndGqq7xtOtMtiTB9vO_eiVfk4Tk7ujmE8XgLLphnmweHR2WXO97lRTC5rGuK86xliQRVB_Gy6VFQhACAPZK";
        Map<String, Object> map = new HashMap<>();
        Map<String, Object> map1 = new HashMap<>();
        Map<String, Object> map2 = new HashMap<>();
        map2.put("value", "2015年01月05日 12:30");
        map1.put("keyword1", map2);
        map2.put("value", "已受理");
        map1.put("keyword2", map2);
        map2.put("value", "30元");
        map1.put("keyword3", map2);
        map.put("data", map1);
        map.put("touser", "ozYvq0C7j66py3OIuV_v30c6j_dY");
        map.put("template_id", "0HlGMGcqwH9jvlLbr4RHwn-NgSmjZcI_-lhUjyRcs-I");
        map.put("form_id", "wx29131806213159f38640a9550qw606");
        map.put("emphasis_keyword", "keyword1.DATA");
        String str = JSON.toJSONString(map);
        System.out.println("str：" + str);
//        String body = sendPostDataByJson(url, str, "utf-8");
//        System.out.println("响应结果：" + body);
    }

    @Test
    public void testSendGetData() throws ClientProtocolException, IOException {
//        String param = "?grant_type=authorization_code" +
//                "&appid=" + "wx971daa8b72f0a9b6" +
//                "&secret=" + "954908329b76f1ecdf5e614d4298a660" +
//                "&js_code=" + "021Dmcmt0RtoTd12Ipjt0FO9mt0Dmcm4";
//
//        String url = "https://api.weixin.qq.com/sns/jscode2session?" +
//                "appid=wx971daa8b72f0a9b6" +
//                "&secret=954908329b76f1ecdf5e614d4298a660" +
//                "&js_code=021Dmcmt0RtoTd12Ipjt0FO9mt0Dmcm4" +
//                "&grant_type=authorization_code";
//        String body = sendGetData(url, "utf-8");
//        System.out.println("响应结果：" + body);

        String url = "https://img.vphotos.cn/B7795DBB07A79D037F4ABC2E690A5DEA/postp/logolarge/vbox4124_IMGL9648_105615_small.JPG";
        String[] split = url.split("/");

        String path = url.substring(23);
        System.out.println("split = " + path);
    }

}
